import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = \
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy()
db.init_app(app)


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

    def __repr__(self):
        return '<Role %r>' % self.name

    users = db.relationship('User', backref='role')


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)

    def __repr__(self):
        return '<User %r>' % self.username

    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))


def print_msg(Role, User):
    print(Role.query.all())
    print(User.query.all())


# 添加对象
def add_user_all(user_list):
    db.session.add_all(user_list)
    db.session.commit()


def del_user_all(user_list):
    for user in user_list:
        db.session.delete(user)
    db.session.commit()


def update_user(user):
    user.username = 'Temp is win'
    db.session.add(user)
    db.session.commit()

# with app.app_context():
#     db.create_all()

# 创建对象
# admin_role = Role(name='Admin')
#
# mod_role = Role(name='Moderator')
#
# user_role = Role(name='User')
#
# user_john = User(username='john', role=admin_role)
#
# user_susan = User(username='susan', role=user_role)
#
# user_david = User(username='david', role=user_role)

# 添加对象
# add_user_all([admin_role, mod_role, user_role,
#               user_john, user_susan, user_david])
# print_msg(Role, User)
#
#     temp_role = Role(name='Temp')
#     user_temp = User(username='temp', role=temp_role)
#     # # 添加对象
#     add_user_all([temp_role, user_temp])
#     print_msg(Role, User)
#
#     # 修改对象
#     update_user(user_temp)
#     print_msg(Role, User)
#
#     # 删除对象
#
#     del_user_all([user_temp, temp_role])
#     print_msg(Role, User)
#
# exit()
